package com.code.google.mdsc.io.csv.impl.threading;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import com.code.google.mdsc.control.Business;
import com.code.google.mdsc.gui.MainWindow;
import com.code.google.mdsc.io.AbstractTask;
import com.code.google.mdsc.io.csv.CSVBookingParser;
import com.code.google.mdsc.io.csv.impl.CSVBookingParserImpl;
import com.code.google.mdsc.io.log.SimpleLogger;
import com.code.google.mdsc.io.log.impl.SimpleLoggerImpl;
import com.code.google.mdsc.model.Booking;
import com.code.google.mdsc.model.Debtor;

public class CSVBookingParserTask extends AbstractTask {

	private static SimpleLogger logger = SimpleLoggerImpl.getInstance();
	private Business business;
	private Booking bookingData = null;

	/**
	 * @param mw
	 * @param business
	 * @param selectedFile
	 */
	public CSVBookingParserTask(MainWindow mw, Business business,
			File selectedFile) {
		super(selectedFile, mw);
		this.business = business;
	}

	@Override
	protected void doAfterDone() {
		if (bookingData != null) {
			business.setCreditorData(bookingData.getCreditor());
			updateTableModel();
		}

	}

	@Override
	protected void doIOOperations() {
		CSVBookingParser csvParser = new CSVBookingParserImpl(this);

		bookingData = csvParser.parse(getSelectedFile());

	}

	private Object[] getColumnHeader() {
		TableColumnModel tcm = getMw().getTable().getColumnModel();
		Object[] columnNames = new Object[tcm.getColumnCount()];
		for (int i = 0; i < columnNames.length; i++) {

			columnNames[i] = tcm.getColumn(i).getHeaderValue();

		}
		return columnNames;
	}

	@Override
	protected void showDialog() {
		JOptionPane.showMessageDialog(getMw().getMainFrame(),
				"reading the csv data finished...");

	}

	private void updateTableModel() {

		// TODO do this while parsing...
		Object[] columnNames = getColumnHeader();

		Object[][] data = new Object[bookingData.getDebtors().size()][columnNames.length];

		DateFormat sdf = SimpleDateFormat.getDateInstance();
		for (int i = 0; i < data.length; i++) {

			logger.log(SimpleLogger.LogMode.DEBUG, "Updating table model "
					+ (i + 1) + "/" + data.length);
			Debtor debtor = bookingData.getDebtors().get(i);
			data[i][0] = debtor.getMandate();
			data[i][1] = debtor.getAccountHolder();
			data[i][2] = debtor.getBookingVolume();
			data[i][3] = sdf.format(debtor.getMandateSignatureDate().getTime());
			data[i][4] = debtor.getUnstructuredPurpose();
			data[i][5] = debtor.getIBAN();
			data[i][6] = debtor.getBIC();
			data[i][7] = sdf.format(bookingData.getDateOfBooking().getTime());
			data[i][8] = debtor.getSequenceType();
		}

		((DefaultTableModel) getMw().getTable().getModel()).setDataVector(data,
				columnNames);

	}

}
